//定义电影演员相关接口
const express = require("express");
const router = express.Router();
//引入mysql连接池
const pool = require("../utils/db");
//引入joi表单验证模块
const Joi = require("joi");
//引入响应对象模块
const Response = require("../utils/Response");
const jwt = require("jsonwebtoken");
const SECRET_KEY = "JWT_SECRET_KEY";
//处理登陆业务
router.post("/user/login", (req, resp) => {
  let { username, password } = req.body;
  //表单验证
  let schema = Joi.object({
    username: Joi.string().required().pattern(new RegExp("^\\w{3,15}$")),
    password: Joi.string().required().pattern(new RegExp("^\\w{6,15}$")),
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return;
  }
  //表单验证通过，执行添加操作
  let sql = "select * from admin where username =? and password=MD5(?)";
  pool.query(sql, [username, password], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result.length == 0) {
      resp.send(Response.error(1001, "账号密码输入错误"));
    } else {
      let user = result[0];
      let payload = { id: user.id, nickname: user.nickname };
      //为该用户颁发一个token字符串，未来改客户端若发送其他请求，则需要在请求Header中携带token，完成状态管理
      let token = jwt.sign(payload, SECRET_KEY, { expiresIn: "1d" });
      //返回user对象与token字符串
      user.password = undefined;
      resp.send(Response.ok({ user, token }));
    }
  });
});

//将Router接口导出
module.exports = router;
